import 'dart:async';
import 'dart:io';
import 'package:audio_session/audio_session.dart';
import 'package:fate_blind_box/config/app_style.dart';
import 'package:fate_blind_box/config/event_bus.dart';
import 'package:fate_blind_box/config/event_keys.dart';
import 'package:fate_blind_box/im/chatPage.dart';
import 'package:fate_blind_box/im/video_model.dart';
import 'package:fate_blind_box/ui/cooperation/shop_code/shop_promote_code_page.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter_sound_platform_interface/flutter_sound_recorder_platform_interface.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:flutter_svg/svg.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:just_audio/just_audio.dart' hide AudioSource;
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class RecordPanel extends StatefulWidget {
  const RecordPanel({
    Key? key,
    required this.onPressedDown,
    required this.onEnd,
    required this.onCancel,
    required this.conversationId,
    this.type = ChatType.Chat,
  }) : super(key: key);

  final VoidCallback onPressedDown;
  final VoidCallback onEnd;
  final VoidCallback onCancel;
  final String conversationId;
  final ChatType type;

  @override
  State<StatefulWidget> createState() => _RecordPanelState();
}

class _RecordPanelState extends State<RecordPanel> {
  bool _recordOnPressed = false;
  OverlayEntry? _overlayEntry;
  late StreamSubscription _streamSubscription;

  /// 声音录制控制器
  FlutterSoundRecorder recorderModule = FlutterSoundRecorder();

  /// 声音播放器
  FlutterSoundPlayer playerModule = FlutterSoundPlayer();
  FlutterSound sound = FlutterSound();
  final player = AudioPlayer();
  VideoModel videoModel = VideoModel();
  RecordPlayState state = RecordPlayState.record;
  int soundLength = 0;

  void buildOverlay(BuildContext context) {
    if (_overlayEntry == null) {
      _overlayEntry = OverlayEntry(builder: (context) {
        return Container(
          color: Colors.transparent,
        );
      });
      Overlay.of(context).insert(_overlayEntry!);
    }
  }

  void removeOverlay() {
    if (_overlayEntry != null) {
      _overlayEntry!.remove();
      _overlayEntry = null;
    }
  }

  @override
  void initState() {
    super.initState();
    // 添加录制监听，成功后发送
    initRecorder();
  }

  @override
  void dispose() {
    super.dispose();
    _streamSubscription.cancel();
  }

  Future<void> initRecorder() async {
    //开启录音
    await recorderModule.openRecorder();
    //设置订阅计时器
    await recorderModule.setSubscriptionDuration(const Duration(seconds: 1));
    //设置音频
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration(
      avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
      avAudioSessionCategoryOptions:
          AVAudioSessionCategoryOptions.allowBluetooth |
              AVAudioSessionCategoryOptions.defaultToSpeaker,
      avAudioSessionMode: AVAudioSessionMode.spokenAudio,
      avAudioSessionRouteSharingPolicy:
          AVAudioSessionRouteSharingPolicy.defaultPolicy,
      avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
      androidAudioAttributes: const AndroidAudioAttributes(
        contentType: AndroidAudioContentType.speech,
        flags: AndroidAudioFlags.none,
        usage: AndroidAudioUsage.voiceCommunication,
      ),
      androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
      androidWillPauseWhenDucked: true,
    ));
    await playerModule.closePlayer();
    await playerModule.openPlayer();
    await playerModule
        .setSubscriptionDuration(const Duration(milliseconds: 10));
  }

  /// 开始录音
  startRecorder() async {
    initRecorder();
    await getPermissionStatus().then((value) async {
      if (!value) {
        return;
      }
      //用户允许使用麦克风之后开始录音
      Directory tempDir = await getTemporaryDirectory();
      var time = DateTime.now().millisecondsSinceEpoch;
      String path = '${tempDir.path}/$time${ext[Codec.aacADTS.index]}';
      //这里我录制的是aac格式的，还有其他格式
      await recorderModule.startRecorder(
        toFile: path,
        codec: Codec.aacADTS,
        bitRate: 8000,
        numChannels: 1,
        sampleRate: 8000,
        audioSource: AudioSource.microphone,
      );

      /// 监听录音
      _streamSubscription = recorderModule.onProgress!.listen((e) {
        var date = DateTime.fromMillisecondsSinceEpoch(
            e.duration.inMilliseconds,
            isUtc: true);
        if (date.second >= 600) {
          if (kDebugMode) {
            print('===>  到达时常停止录音');
          }
          stopRecorder();
        }
        soundLength = date.second;
        if (kDebugMode) {
          print('已经开始录音了===时长==${date.second}');
        }
      });
    });
  }

  /// 结束录音
  Future<String?> stopRecorder() async {
    var s = await recorderModule.stopRecorder();
    state = RecordPlayState.record;
    _streamSubscription.cancel();
    return s;
  }

  /// 发送前准备
  readyToSend() async {
    var s = await stopRecorder();
    print('录音链接:$s=====${widget.type}');
    if (videoModel.isStop) {
      if (videoModel.indexPopTime.difference(videoModel.lastPopTime) <
          const Duration(milliseconds: 500)) {
        if (s.toString().isEmpty) {
          EasyLoading.showToast('语音异常,请重新录制');
          return;
        }
        createMessage(filePath: s.toString());
      } else {
        if (kDebugMode) {
          print('点击结束');
        }
      }
    }
  }

  /// 创建语音消息
  createMessage({required String filePath}) {
    EMMessage message = EMMessage.createVoiceSendMessage(
      targetId: widget.conversationId,
      filePath: filePath,
      duration: soundLength,
      chatType: widget.type,
    );
    sendMessage(message);
  }

  /// 发送消息
  sendMessage(EMMessage message) async {
    bool status = await EMClient.getInstance.isConnected();
    if (status) {
      EMClient.getInstance.chatManager.sendMessage(message).then((value) async {
        player.setAsset('images/music_send.mp3');
        final session = await AudioSession.instance;
        session.configure(const AudioSessionConfiguration.music());
        player.play();
        EventBus.instance
            .commit(eventName: EventKeys.chatUpdateAudioMessage, data: message);
      });
    } else {
      ThemeSnackBar.show(context, '已断线,请重新登陆~');
      await EMClient.getInstance
          .login(Provider.userEaseName, Provider.userEaseToken, false);
      FocusScope.of(context).unfocus();
    }
  }

  ///动态获取权限
  Future<bool> getPermissionStatus() async {
    Permission permission = Permission.microphone;
    //granted 通过，denied 被拒绝，permanentlyDenied 拒绝且不在提示
    PermissionStatus status = await permission.status;
    if (status.isGranted) {
      return true;
    } else if (status.isDenied) {
      requestPermission(permission);
    } else if (status.isPermanentlyDenied) {
      openAppSettings();
    } else if (status.isRestricted) {
      requestPermission(permission);
    } else {}
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.topCenter,
      children: [
        Positioned(
          top: 0,
          child: Text(
            _recordOnPressed ? "松开发送，按住滑到空白区域取消" : '',
            style: TextStyle(fontSize: 12.sp, color: '999999'.stringToColor),
          ),
        ),
        Positioned(
          top: 30,
          child: Visibility(
              visible: _recordOnPressed, child: const RecordButtonWave()),
        ),
        Positioned(
          top: 30,
          child: Column(
            children: [
              GestureDetector(
                onLongPressCancel: () {
                  _recordOnPressed = false;
                  removeOverlay();
                  recorderModule.stopRecorder();
                  // _audioService.cancelRecord();
                  widget.onCancel();
                  setState(() {});
                },
                onLongPressDown: (LongPressDownDetails details) {
                  videoModel.sentimer();
                  _recordOnPressed = true;
                  // _audioService.startRecord(AudioOutputFormat.AAC, 60);
                  startRecorder();
                  buildOverlay(context);
                  widget.onPressedDown();
                  setState(() {});
                },
                onLongPressEnd: (LongPressEndDetails details) {
                  _recordOnPressed = false;
                  removeOverlay();
                  double r = 51.5;
                  double dx = (details.localPosition.dx - r).abs();
                  double dy = (details.localPosition.dy - r).abs();
                  if (dx * dx + dy * dy > r * r) {
                    // _audioService.cancelRecord();
                    recorderModule.stopRecorder();
                    widget.onCancel();
                  } else {
                    // _audioService.stopRecord();
                    readyToSend();
                    widget.onEnd();
                  }
                  setState(() {});
                },
                child: Container(
                  padding: const EdgeInsets.all(33.5),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(51.5),
                      gradient: const LinearGradient(
                          colors: [Color(0xffF8893B), Color(0xffF06331)])),
                  child: SvgPicture.asset(
                    'images/ic_record.svg',
                    width: 36,
                    height: 36,
                    color: _recordOnPressed
                        ? const Color(0x7fffffff)
                        : Colors.white,
                  ),
                ),
              ),
              const SizedBox(
                height: 12,
              ),
              Text(
                _recordOnPressed ? "" : '按住说话',
                style:
                    TextStyle(fontSize: 12.sp, color: '#999999'.stringToColor),
              )
            ],
          ),
        ),
      ],
    );
  }
}

class RecordButtonWave extends StatefulWidget {
  const RecordButtonWave({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _RecordButtonWaveState();
}

class _RecordButtonWaveState extends State<RecordButtonWave>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _widthAnimation;

  @override
  void initState() {
    _controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 1000))
      ..repeat();

    _widthAnimation = Tween(begin: 1.0, end: 1.5)
        .animate(CurvedAnimation(parent: _controller, curve: Curves.ease));

    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ScaleTransition(
      scale: _widthAnimation,
      child: Container(
        height: 103,
        width: 103,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(51.5),
            color: const Color(0x4d518ef8)),
      ),
    );
  }
}
